package com.dadie.dorm.controller;


import com.dadie.dorm.util.JSONUtil;
import com.dadie.dorm.util.Result;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("UploadServlet.service");
        //1DiskFileItemFactory磁盘文件项工厂：一些
        DiskFileItemFactory factory=new DiskFileItemFactory();
        //
        factory.setSizeThreshold(10*1024*1024);
        String tempPath= getServletContext().getRealPath("temp");
        //设置临时文件
        factory.setRepository(new File(tempPath));

        //文件上传的核心类
        ServletFileUpload servletFileUpload=new ServletFileUpload(factory);
        //设置文件上传名的编码方式
        servletFileUpload.setHeaderEncoding("UTF-8");
        String fileName="";
        if(ServletFileUpload.isMultipartContent(req)){
            try {
                List<FileItem> fileItems= servletFileUpload.parseRequest(req);
                if(fileItems!=null){
                    for (FileItem fileItem : fileItems) {
                        //如果是普通的表单项目：name:zhangsan
                        if(!fileItem.isFormField()){
                            //文件上传
                            //fileItem封装了前台传递过来的文件上传的相关信息
                            //abc.png
                            String name=fileItem.getName();
                            String extension = FilenameUtils.getExtension(name);
                            String uuid = UUID.randomUUID().toString().replace("_", "");
                            fileName=uuid+"."+ extension;
                            InputStream inputStream=fileItem.getInputStream();
                            OutputStream outputStream=new FileOutputStream("D:/mypic/"+fileName);
                            IOUtils.copy(inputStream,outputStream);
                            outputStream.close();
                            inputStream.close();
                            fileItem.delete();
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }
        JSONUtil.toJSON(resp, Result.ok("上传成功",fileName));
    }
}
